﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;

using RTGS.Library.Entities.UserManagement;
using RTGS.Library.DataAccess.UserManagement;

using RTGS.Web.support;

using System.Configuration;
using System.Text;

namespace RTGS.Web
{

   public partial class Rtgs : BaseMasterPage
    {
        Membership membership = new Membership(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        sysTRoleRepo roleDal = new sysTRoleRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Header.DataBind();  
            LinkLogout.HRef = support.Helper.GetAppVirtualPath(this.Page) + "/form/authentication/logout.aspx";
            ltrUserName.Text = base.UserLoggedIn;

            LoadMenu(base.UserID);
            LoadSiteMap(base.MenuID);


        }

        private void LoadMenu(int userId)
        {
            List<int> roleIds = new List<int>();

            membership.GetRoles(userId).ForEach(delegate(sysTUserRole role)
            {
                roleIds.Add(role.roleId.Value);
            });

            var satKer = base.UserLoggedIn.ToLower().Contains("admin") ? "" : base.DeskripsiSatker;

            //ltrSatKer.Text = satKer;            

            List<sysTMenu> menus = membership.GetMenusByRoleIDs(roleIds);

            mnMaster.Items.Clear(); // Clear Menu Items
            AddItems(mnMaster.Items, null, menus); // set Null for the first time to load BaseParent.

        }

        private void LoadSiteMap(int menuId)
        {
            sysTMenuRepo menuDal = new sysTMenuRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

            var currentMenu = menuDal.GetHierarchyList("WHERE m.Menu_Id = " + menuId);
           
            StringBuilder sbSitemap = new StringBuilder();

            sbSitemap.AppendFormat("<li><a href=\"{0}\" title=\"Home\">", support.Helper.GetAppVirtualPath(this.Page) + "/index.aspx");
            sbSitemap.AppendFormat("<img src=\"{0}\" alt=\"Home\" class=\"home\" />", ResolveClientUrl("images/breadcrumb/home.gif"));
            sbSitemap.Append("</a></li>");

            Stack<sysTMenu> siteMenus = new Stack<sysTMenu>();

            if (currentMenu.Count > 0)
            {
                var count = Convert.ToInt32(currentMenu[0].level)+1;

                var currentId = currentMenu[0].menuId;

                for (var i = 0; i < count; i++)
                {
                    sysTMenu dto = menuDal.GetById(currentId);
                    if (dto.menuId > 0)
                    {
                        siteMenus.Push(dto);
                        currentId = (dto.parentId.HasValue) ? dto.parentId.Value : 0;
                    }
                }

                foreach (sysTMenu dto in siteMenus)
                {
                    var navigateUrl = (string.IsNullOrEmpty(dto.url) ? "#" : dto.url + (dto.url.Contains('?') ? "&menuid=" + dto.menuId : "?menuid=" + dto.menuId));
                    if (dto.menuId == currentMenu[0].menuId)
                        sbSitemap.AppendFormat("<li>{0}</li>", dto.menuName);
                    else
                        sbSitemap.AppendFormat("<li><a href=\"{0}\" title=\"{1}\">{1}</a></li>", navigateUrl, dto.menuName);
                }

            }

            ltrSiteMap.Text = sbSitemap.ToString();
        }

        private void AddItems(MenuItemCollection items, decimal? id, List<sysTMenu> menus)
        {
            var getParents = menus.Where(x => x.parentId == id).OrderBy(x => x.orderSeq);

            foreach (sysTMenu menu in getParents)
            {
                MenuItem item = new MenuItem()
                {
                    Text = menu.menuName,
                    NavigateUrl = (string.IsNullOrEmpty(menu.url) ? string.Empty : menu.url + (menu.url.Contains('?') ? "&menuid=" + menu.menuId : "?menuid=" + menu.menuId))
                };

                this.AddItems(item.ChildItems, menu.menuId, menus);
                items.Add(item);
            }
        }
    
    }

}